package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.vo.SkuPriceVo;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.service.IProductSkuService;
import com.spzx.product.api.vo.ProductSkuVo;
import com.spzx.product.vo.SkuQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-12-19
 */
@Service
@Slf4j
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    @Override
    public List<ProductSkuVo> getTopSale() {
        return baseMapper.selectTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {
        // 根据skuId查询商品价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(ProductSku::getId, skuId)
                .select(ProductSku::getSalePrice, ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);
        // 封装数据
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setSkuId(skuId);
        return skuPriceVo;
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        // 查询一个商品的所有sku
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(ProductSku::getProductId, id)
                .select(ProductSku::getId, ProductSku::getSkuSpec);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);
        // 封装数据
        Map<String,Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ProductSku getProductSku(Long skuId) {
        try {
            //1.优先从缓存中获取数据
            //1.1 构建业务数据Key 形式：前缀+业务唯一标识
            String key = "product:sku:" + skuId;

            ProductSku productSku = new ProductSku();
            //1.2 查询Redis获取业务数据
            productSku = (ProductSku) redisTemplate.opsForValue().get(key);
            if (productSku != null) {
                //2.缓存命中，直接返回(打印日志)
                log.info("命中缓存，直接返回，线程ID：{}，线程名称：{}",
                        Thread.currentThread().getId(),
                        Thread.currentThread().getName());
                return productSku;
            }
            //2.缓存中没有，从数据库中查询
            productSku = baseMapper.selectById(skuId);
            if (productSku != null) {
                //3.将查询到的数据放入缓存中
                redisTemplate.opsForValue().set(key, productSku);
                return productSku;
            }

            //2.尝试获取分布式锁（set k v nx ex 可能获取锁失败）
            //2.1 构建锁key
            String lockKey = "product:sku:lock:" + skuId;
            //2.2 采用UUID作为线程标识
            String uuid = UUID.randomUUID().toString();
            //2.3 利用Redis提供set nx ex 获取分布式锁
            Boolean flag = redisTemplate
                    .opsForValue()
                    .setIfAbsent(lockKey, uuid, 30, TimeUnit.SECONDS);
            if (Boolean.TRUE.equals(flag)) {
                //3.获取锁成功执行业务,将查询业务数据放入缓存Redis
                log.info("获取锁成功：{}，线程名称：{}",
                        Thread.currentThread().getId(),
                        Thread.currentThread().getName());
                try {
                    //3.1 再次检查缓存里面是否已经存在数据
                    productSku = (ProductSku) redisTemplate.opsForValue().get(key);
                    if (productSku != null) {
                        //3.2 缓存命中，直接返回(打印日志)
                        log.info("命中缓存，直接返回，线程ID：{}，线程名称：{}",
                                Thread.currentThread().getId(),
                                Thread.currentThread().getName());
                        return productSku;
                    }
                    productSku = baseMapper.selectById(skuId);
                    //防止缓存穿透，将null值转换成新对象存入数据库，并且设置较短的过期时间
                    long ttl = productSku == null ? 1 * 60 : 10 * 60;
                    if (productSku == null) {
                        productSku = new ProductSku();
                    }
                    //将查询数据库结果放入缓存
                    redisTemplate
                            .opsForValue()
                            .set(key, productSku, ttl, TimeUnit.SECONDS);
                    return productSku;
                } finally {
                    //4.业务执行完毕使用Lua脚本释放锁
                    String script = """
                            if redis.call('get', KEYS[1]) == ARGV[1] 
                            then
                                return redis.call('del', KEYS[1])
                            else return 0 
                            end
                            """;
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    redisScript.setScriptText(script);
                    redisScript.setResultType(Long.class);
                    redisTemplate.execute(redisScript,
                            List.of(lockKey),
                            uuid);
                }
            } else {
                try {
                    //5.获取锁失败，自旋重试
                    log.info("获取锁失败，自旋重试，线程ID：{}，线程名称：{}",
                            Thread.currentThread().getId(),
                            Thread.currentThread().getName());
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                log.error("获取锁失败，自旋：{}，线程名称：{}",
                        Thread.currentThread().getId(),
                        Thread.currentThread().getName());
                return this.getProductSku(skuId);
            }
        }catch (Exception e) {
            //兜底处理方案：Redis服务有问题，将业务数据获取自动从数据库获取
            log.error("[商品服务]查询商品信息异常：{}", e);
            return baseMapper.selectById(skuId);
        }

    }



    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        //1.查询数据库
        List<ProductSku> productSkuList = baseMapper.selectList(
                new LambdaQueryWrapper<ProductSku>()
                        .in(ProductSku::getId, skuIdList)
                        .select(ProductSku::getId, ProductSku::getSalePrice)
        );
        //2.将查询结果封装成SkuPriceVo
        return productSkuList.stream().map(item -> {
            SkuPriceVo skuPrice = new SkuPriceVo();
            skuPrice.setSkuId(item.getId());
            skuPrice.setSalePrice(item.getSalePrice());
            return skuPrice;
        }).collect(Collectors.toList());
    }



}
